<template>
  <div class="source-form-component">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="source-form"
    >
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- 左侧：基本信息 -->
        <el-card shadow="never" class="form-card">
          <template #header>
            <h3 class="text-lg font-semibold">基本信息</h3>
          </template>
          
          <div class="space-y-6">
            <el-form-item v-if="mode === 'edit'" label="新闻源ID">
              <el-input v-model="formData.id" disabled />
            </el-form-item>

            <el-form-item label="新闻源名称" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入新闻源名称，如：新华网、人民网"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="新闻源代码" prop="code">
              <el-input
                v-model="formData.code"
                placeholder="请输入新闻源代码，如：xinhua、people"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="主页链接" prop="homepage">
              <el-input
                v-model="formData.homepage"
                placeholder="请输入新闻源主页链接"
                maxlength="255"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="所属区域" prop="regionId">
              <el-select
                v-model="formData.regionId"
                placeholder="请选择所属区域"
                class="w-full"
                @change="handleRegionChange"
              >
                <el-option
                  v-for="region in regionOptions"
                  :key="region.id"
                  :label="region.name"
                  :value="region.id"
                />
              </el-select>
              <div v-if="formData.regionName" class="mt-1 text-sm text-gray-500">
                当前区域：{{ formData.regionName }}
              </div>
            </el-form-item>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <el-form-item label="排序" prop="sortOrder">
                <el-input-number
                  v-model="formData.sortOrder"
                  :min="0"
                  :max="999"
                  class="w-full"
                />
              </el-form-item>

              <el-form-item label="状态" prop="status">
                <el-switch
                  v-model="formData.status"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </div>

            <el-form-item label="描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入新闻源描述信息（可选）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>
        </el-card>

        <!-- 右侧：元数据 -->
        <el-card shadow="never" class="form-card">
          <template #header>
            <h3 class="text-lg font-semibold">元数据</h3>
          </template>
          <div class="space-y-4">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="ID">
                <span>{{ formData.id ?? '-' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="区域名称">
                <span>{{ getRegionName(formData.regionId) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                <span>{{ formatDateTime(formData.createdAt) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="修改时间">
                <span>{{ formatDateTime(formData.updatedAt) }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { regionAPI } from '~/services/api'

const props = defineProps({
  mode: {
    type: String,
    required: true,
    validator: (value) => ['add', 'edit'].includes(value)
  },
  sourceId: {
    type: [String, Number],
    default: null
  },
  initialData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['save', 'delete', 'cancel'])
const formRef = ref()
const regionOptions = ref([])

const formData = reactive({
  id: null,
  name: '',
  code: '',
  homepage: '',
  regionId: null,
  regionName: '',
  description: '',
  sortOrder: 0,
  status: 1,
  createdAt: '',
  updatedAt: ''
})

const formRules = {
  name: [
    { required: true, message: '请输入新闻源名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[^\s]+$/, message: '名称不能包含空格', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入新闻源代码', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_]*$/, message: '代码必须以小写字母开头，只能包含小写字母、数字和下划线', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  homepage: [
    { required: true, message: '请输入主页链接', trigger: 'blur' },
    { pattern: /^https?:\/\/.+/, message: '请输入有效的URL地址', trigger: 'blur' }
  ],
  regionId: [
    { required: true, message: '请选择所属区域', trigger: 'change' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 0, max: 999, message: '排序值必须在 0 到 999 之间', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择新闻源状态', trigger: 'change' }
  ]
}

const loadRegionOptions = async () => {
  try {
    const result = await regionAPI.getAllRegions()
    if (result.code === 200) {
      regionOptions.value = result.data || []
    }
  } catch (error) {
    console.error('加载区域选项失败:', error)
    ElMessage.error('加载区域选项失败')
  }
}

const handleRegionChange = (regionId) => {
  const region = regionOptions.value.find(r => r.id === regionId)
  if (region) {
    formData.regionName = region.name
  }
}

const getRegionName = (regionId) => {
  if (!regionId) return '-'
  const region = regionOptions.value.find(r => r.id === regionId)
  return region ? region.name : '-'
}

const initFormData = () => {
  if (props.mode === 'add') {
    Object.assign(formData, {
      id: null,
      name: '',
      code: '',
      homepage: '',
      regionId: null,
      regionName: '',
      description: '',
      sortOrder: 0,
      status: 1,
      createdAt: '',
      updatedAt: ''
    })
  } else if (props.mode === 'edit' && props.initialData) {
    Object.assign(formData, props.initialData)
  }
}

const validate = async () => {
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}

const getFormData = () => {
  return { ...formData }
}

const resetForm = () => {
  formRef.value?.resetFields()
  initFormData()
}

const handleSave = async () => {
  try {
    await validate()
    const data = getFormData()
    emit('save', data)
    return true
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
    return false
  }
}

const handleDelete = async () => {
  try {
    emit('delete', formData.id)
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

const handleCancel = () => {
  emit('cancel')
}

watch(() => props.initialData, () => {
  if (props.mode === 'edit') {
    initFormData()
  }
}, { deep: true })

onMounted(() => {
  loadRegionOptions()
  initFormData()
})

defineExpose({
  formRef,
  formData,
  validate,
  getFormData,
  resetForm,
  handleSave,
  handleDelete,
  handleCancel
})

function formatDateTime(val) {
  if (!val) return '-'
  try {
    const d = new Date(val)
    if (Number.isNaN(d.getTime())) return String(val)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch {
    return String(val)
  }
}
</script>

<style scoped>
.source-form-component {
  @apply w-full;
}

.form-card {
  @apply border border-gray-200;
}

.form-card :deep(.el-card__header) {
  @apply bg-gray-50 border-b border-gray-200;
}

.source-form :deep(.el-form-item__label) {
  @apply text-gray-700 font-medium;
  line-height: 28px;
}

.source-form :deep(.el-input-number) {
  @apply w-full;
}

.form-card :deep(.el-descriptions__label) {
  @apply w-24;
}
</style>
